package com.jolink.omiis.wechat.outer.custom;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.gson.JsonObject;
import com.jolink.omiis.wechat.WeChatContext;
import com.jolink.omiis.wechat.inner.IOmiisMessager;
import com.jolink.omiis.wechat.outer.AbstractWeChatController;
import com.jolink.omiis.wechat.outer.MessageWorker;
import com.jolink.omiis.wechat.outer.WeChatResponse;
import com.jolink.omiis.wechat.util.GsonUtil;

/**
 * 58-M站
 * @author WangYanqing
 *
 */
@Controller
@RequestMapping("/customer/query")
public class WeChat58Controller extends AbstractWeChatController {
	private static Logger logger = LoggerFactory.getLogger(WeChat58Controller.class);

	@Autowired
	private ThreadPoolTaskExecutor taskExecutor;

	@Autowired
	private WeChatContext context;

	@Autowired
	private IOmiisMessager messager;

	@RequestMapping(method = RequestMethod.GET)
	public void get(HttpServletRequest request, HttpServletResponse response) {
		long t1 = System.currentTimeMillis();
		logger.info("接收到58-M站点请求：{}，InstanceId：{}", request.getParameterMap(), this.hashCode());
		try {
			String code = request.getParameter("code");
			String state = request.getParameter("state");
			String appId = request.getParameter("appId");
			JsonObject rootJson = new JsonObject();
			rootJson.addProperty("errorCode", "0");
			rootJson.addProperty("errorMessage", "ok");
			rootJson.addProperty("openId", "123456789");
			rootJson.addProperty("nickName", "9527");
			rootJson.addProperty("gender", "male");
			String responseMessage = GsonUtil.jsonElement2Json(rootJson);
			logger.info("响应服务器内容：{}", responseMessage);
			response.getWriter().write(responseMessage);
			response.getWriter().flush();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			try {
				response.getWriter().write("");
			} catch (IOException e1) {
				logger.error(e.getMessage(), e);
			}
			return;
		}
		long t2 = System.currentTimeMillis();
		logger.info("处理58-M请求完成，结果：{}，耗时：{}毫秒。", "", (t2 - t1));
	}

	@RequestMapping(value = "{APPID}", method = RequestMethod.POST)
	public void post(@PathVariable String APPID, HttpServletRequest request, HttpServletResponse response) {
		long t1 = System.currentTimeMillis();
		logger.info("接收到腾讯普通信息请求：{}，InstanceId：{}，APPID：{}，CharacterEncoding：{}", request.getParameterMap(),
				this.hashCode(), APPID, request.getCharacterEncoding());
		String requestBody = null;
		WeChatResponse wr = null;
		try {
			response.setHeader("Cache-Control", "no-cache");
			response.setHeader("Prama", "no-cache");
			response.setContentType("text/xml;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			requestBody = readBody(request);
			if (StringUtils.isEmpty(requestBody)) {
				throw new RuntimeException("信息为空！");
			}
			// String decryptMsg = decrypt(request.getParameterMap(),
			// requestBody);
			// logger.info("开始异步处理请求信息，请求信息：{}，明文：{}", decryptMsg);
			logger.info("开始异步处理微信请求，请求内容：{}。", requestBody);

			// IMessageHandler messageHandler =
			// createMessageHandler(request.getParameterMap(), requestBody);
			// wr = messageHandler.handleMessage();
			// logger.info("请求信息处理完成，返回内容：{}。", GsonUtil.obj2Json(wr));
			// logger.info("返回处理结果：{}", wr.getResponseMsg());
			taskExecutor.execute(new MessageWorker(context, request.getParameterMap(), requestBody, messager));
			// int contentLength = wr.getResponseMsg().trim().length();
			// response.setHeader("Content-Length",
			// String.valueOf(contentLength));
			// response.getWriter().write(wr.getResponseMsg().trim());
			response.getWriter().write("success");
			response.flushBuffer();
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			try {
				response.getWriter().write("");
			} catch (IOException e1) {
				logger.error(e.getMessage(), e);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			try {
				response.getWriter().write("");
			} catch (IOException e1) {
				logger.error(e.getMessage(), e);
			}
		}
		long t2 = System.currentTimeMillis();
		logger.info("处理腾讯普通信息请求完成，耗时：{}毫秒。", (t2 - t1));
	}
}
